import 'package:flutter/material.dart';
import 'dart:async';
class FFCountDownBtn extends StatefulWidget {

  final int total ;
  final double width;
  final double height;
  final Color  normalBackgroundColor;
  final Color  disabledBackgroundColor;
  final String showText;
  final VoidCallback onpress;
  static const nbgColor = Color.fromRGBO(221, 221, 221, 1.0);
  FFCountDownBtn({
    this.total,
    this.width = 80,
    this.height = 30,
    this.showText = "发送",
    this.onpress,
    this.normalBackgroundColor = nbgColor,
    this.disabledBackgroundColor = nbgColor,
  });

  @override
  State<StatefulWidget> createState() {
    return FFCountDownBtnState();
  }

}

class FFCountDownBtnState extends State<FFCountDownBtn> {

  Timer _timer;
  int sur;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    creatTimer();
  }

  @override
  void dispose() {
    _timer?.cancel();
    super.dispose();
  }

  void creatTimer() {
    sur = widget.total;
    _timer = Timer.periodic(Duration(milliseconds: 1000), (ti){
      setState(() {
        sur -= 1;
        if (sur == 0) {
          _timer.cancel();
        }
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      width: widget.width,
      child: Center(
        child:Container(
          width:widget.width,
          height: 30,
          decoration: BoxDecoration(
            color: widget.disabledBackgroundColor,
            borderRadius: BorderRadius.circular(8),
          ),
          child: FlatButton(
            onPressed:(){
              if(sur == 0) {
                creatTimer();
                widget.onpress();
              }
            },
            child: Text(
              sur == 0 ? widget.showText : '$sur s',
              style:TextStyle(color: Colors.black, fontSize:16.0),
            )),
        )
      ),
    );
  }
  
}